package com.hyou.springboot.interceptor;

import java.io.PrintWriter;
import java.io.Serializable;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.hyou.common.util.json.JsonUtil;
import com.hyou.springboot.base.ResponseMessage;
import com.hyou.springboot.util.ResponseMessageUtil;
import com.hyou.springboot.util.SessionCacheUtil;

/**
 * 权限校验拦截器。
 * 
 * @author HyouSeki
 * @version 1.0.0 2018-12-17 14:36:03 初始创建
 */
public class AuthInterceptor extends HandlerInterceptorAdapter {
    
    /**
     * log
     */
    private static final Logger log = LoggerFactory.getLogger(AuthInterceptor.class);
    
    @Resource
    private RedisTemplate<String, String> redisTemplate;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        
        String path = request.getServletPath();
        log.debug("request servlet path : {}", path);
        
        if (!SessionCacheUtil.hasSession()) {
            log.debug("未登录或Session过期");
            printJsonMsg(response, ResponseMessageUtil.genLoginTimeoutResult());
            return false;
        }
        
        if (!SessionCacheUtil.hasAttribute(path)) {
            log.debug("缺少权限： {}", path);
            printJsonMsg(response, ResponseMessageUtil.genNoPermissionResult());
            return false;
        }
        
        return true;
    }
    
    private static void printJsonMsg(HttpServletResponse res, ResponseMessage<Serializable> msg) {
        res.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        
        try (PrintWriter out = res.getWriter()) {
            out.write(JsonUtil.toJSONString(msg));
            out.flush();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
    
}
